package com.agua.enturno.vista.paginas.login;

import com.agua.enturno.excepciones.ExcepcionDeReglaDelNegocio;
import com.agua.enturno.servicios.UsuarioService;
import com.agua.enturno.vista.dto.UsuarioDTO;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.EmailAddressValidator;

public class RegistrationPanel extends Panel {

	private static final long serialVersionUID = 1L;
	
	@SpringBean
	private UsuarioService usuarioService;
	
	public RegistrationPanel(String id, final IModel<UsuarioDTO> model) {
		super(id, model);
		this.setOutputMarkupId(true);
		
		FeedbackPanel feedbackPanel = new FeedbackPanel("local-feedback");
		feedbackPanel.setMaxMessages(1);
		add(feedbackPanel);
		
		@SuppressWarnings("rawtypes")
		Form form = new Form("registration-form");
		
    	form.add(new AjaxButton("boton-registrar") {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				
				try {
					usuarioService.crearUsuario(model.getObject());
					info("Su usuario se ha registrado satisfactoriamente");
				} catch (ExcepcionDeReglaDelNegocio e) {
					error(e.getMessage());
				}
				target.add(RegistrationPanel.this);	
			}
			
			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(RegistrationPanel.this);	
			}
		});
    	
    	form.add(new Button("boton-limpiar") {
            private static final long serialVersionUID = 1L;

			@Override
            public void onSubmit() {
                setResponsePage(RegistrationPage.class);
            }
        }.setDefaultFormProcessing(false));
		
		PasswordTextField passwordField = new PasswordTextField("password", new PropertyModel<String>(model, "password"));
		passwordField.setResetPassword(false);
		
		TextField<String> emailField = new RequiredTextField<String>("email", new PropertyModel<String>(model, "email"));
		emailField.add(EmailAddressValidator.getInstance());
		
		form.add(new RequiredTextField<String>("nombre", new PropertyModel<String>(model, "nombre")));
		form.add(emailField);
		form.add(passwordField);
		form.add(new TextField<String>("telefono", new PropertyModel<String>(model, "telefono")));
		
		add(form);
	}

}
